import Loading from './loading';
import { createRoot } from 'react-dom/client';

let root: ReturnType<typeof createRoot> | null = null;
let requestCount = 0;

const rootElement = document.getElementById('custom-loading');
if (rootElement) {
  root = createRoot(rootElement);
}

export const showLoading = ({ tip = 'loading' }: { tip?: string }) => {
  if (root && requestCount === 0) {
    root.render(<Loading tip={tip} />);
  }
  requestCount++;
};

export const hideLoading = () => {
  if (root) {
    requestCount--;
    console.log('hideLoading', requestCount);
    if (requestCount <= 0) {
      root.render(<div />);
      requestCount = 0; // 确保计数器不会变成负数
    }
  }
};